package com.walker.workqueue;

import com.rabbitmq.client.*;
import com.walker.BaseConfig;

import java.io.Console;
import java.io.IOException;

/**
 * @Description:
 * @ProjectName: walker-step
 * @Package: com.walker.workqueue
 * @ClassName: WorkQueueSender
 * @Author: yangyl
 * @CreateDate: 2020/6/20 20:55
 */
public class WorkQueueResv {


    public static ConnectionFactory connectionFactory() {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(BaseConfig.HOST);
        connectionFactory.setVirtualHost(BaseConfig.VHOST);
        connectionFactory.setPort(5672);
        connectionFactory.setUsername(BaseConfig.USERNAME);
        connectionFactory.setPassword(BaseConfig.PASSWORD);
        return connectionFactory;
    }

    public static void main(String[] args) throws Exception {
        ConnectionFactory connectionFactory = connectionFactory();
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare("hello", true, false, false, null);
        //todo 只处理一个消息
        channel.basicQos(1);
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String body = new String(message.getBody(), "UTF-8");
                System.out.println(" Received '" + body + "'");
                try {
                    doWork(body);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    System.out.println("结束消息");
                    channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
                }
            }
        };

        //todo 不自动确认 改手动确认
        channel.basicConsume("hello", false, deliverCallback, consumerTag ->
        {
        });
    }

    private static void doWork(String task) throws InterruptedException {
        for (char ch : task.toCharArray()) {
            if (ch == '.') Thread.sleep(1000);
        }
    }

}
